package com.nytd.demo.common.advice;

import com.nytd.demo.common.exception.BlogException;
import com.nytd.demo.pojo.response.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.stream.Collectors;


@Slf4j
@ResponseBody
@ControllerAdvice
public class ExceptionAdvice {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getAllErrors()
                .stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining("; "));

        return Result.fail(400, message);
    }

    @ExceptionHandler(BlogException.class)
    public Result handler(BlogException e) {
        log.info("业务异常: {}", e.getMessage());
        return Result.fail(e.getCode(), e.getMessage()); // 使用异常中的错误码
    }

    @ExceptionHandler(Exception.class)
    public Result handler(Exception e) {
        log.error("系统异常: {}", e.getMessage()); // 记录完整堆栈
        return Result.fail(e.getMessage());
    }




}
